package com.zan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zan.dao.MenuMapper;
import com.zan.dao.UserMapper;
import com.zan.entity.LoginUser;
import com.zan.entity.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @Author Zan
 * @Date 2023/10/17 13:38
 * @Description :
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名去查询对应的用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        // 如果没有查询到用户就抛出异常
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或者密码错误");
        }

        // 由于一个用户可能既是前端开发人员，又是后端开发人员，相当于一个人有多个角色，会有不同的权限，因此这里接收的是一个List<String>字符串集合
        // 从数据库查询权限信息
        List<String> list = menuMapper.selectPermsByUserId(user.getId());
//        List<String> list = new ArrayList<>(Arrays.asList("test", "admin"));

        // 把对应的用户信息包括权限信息封装成UserDetails返回
        return new LoginUser(user, list);
    }
}
